<template>
  <div class="view-result">
    <!-- 系统建议配置 -->
    <div class="section recommended-config">
      <div class="section-title">系统建议配置</div>
      <div class="config-grid">
        <div class="config-item">
          <div class="config-label">建议储能规划容量</div>
          <div class="config-value">
            {{
              finalResultData?.suggestPlanCapacity !== null &&
              finalResultData?.suggestPlanCapacity !== undefined
                ? formatNumber(finalResultData.suggestPlanCapacity) + ' kWh'
                : '- kWh'
            }}
          </div>
        </div>
        <div class="config-item">
          <div class="config-label">PCS功率建议值</div>
          <div class="config-value">
            {{
              finalResultData?.pcsRecommendValue
                ? finalResultData.pcsRecommendValue + ' kW'
                : '-'
            }}
          </div>
        </div>
        <div class="config-item">
          <div class="config-label">预计投资回报年限</div>
          <div class="config-value">
            {{
              finalResultData?.expectedInvestReturnPeriod !== null &&
              finalResultData?.expectedInvestReturnPeriod !== undefined
                ? formatNumber(finalResultData.expectedInvestReturnPeriod) +
                  ' 年'
                : '- 年'
            }}
          </div>
        </div>
        <div class="config-item">
          <div class="config-label">平均日充放电次数</div>
          <div class="config-value">
            {{
              finalResultData?.avgDayChargeDischargeTimes !== null &&
              finalResultData?.avgDayChargeDischargeTimes !== undefined
                ? formatNumber(finalResultData.avgDayChargeDischargeTimes) +
                  ' 次'
                : '- 次'
            }}
          </div>
        </div>
      </div>
    </div>

    <!-- 系统参数 -->
    <div class="section system-params">
      <div class="section-title">系统参数</div>
      <div class="params-grid">
        <div class="param-item">
          <span class="param-label">未来负荷增长:</span>
          <span class="param-value">{{
            formatPercentage(systemParams.futureLoadGrowthRatio)
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">电池充放效率:</span>
          <span class="param-value">{{
            formatPercentage(systemParams.batteryEfficiency)
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">防过载:</span>
          <span class="param-value">{{
            systemParams.antiOverloadFlag ? '是' : '否'
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">满充满放天数:</span>
          <span class="param-value"
            >{{ systemParams.fullChargeFullDischargeDay || '-' }} 天</span
          >
        </div>
        <div class="param-item">
          <span class="param-label">PCS效率:</span>
          <span class="param-value">{{
            formatPercentage(systemParams.pcsEfficiency)
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">防逆流:</span>
          <span class="param-value">{{
            systemParams.backflowPreventionFlag ? '是' : '否'
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">系统单瓦造价:</span>
          <span class="param-value"
            >{{ formatNumber(systemParams.singleWattCost) }} 元/Wh</span
          >
        </div>
        <div class="param-item">
          <span class="param-label">其他效率:</span>
          <span class="param-value">{{
            formatPercentage(systemParams.otherEfficiency)
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">充放电次数:</span>
          <span class="param-value">
            {{
              systemParams.chargeDischargeTimesType === 1
                ? '一充一放'
                : '两充两放'
            }}
          </span>
        </div>
        <div class="param-item">
          <span class="param-label">可放电深度:</span>
          <span class="param-value">{{
            formatPercentage(systemParams.dischargeDepth)
          }}</span>
        </div>
        <div class="param-item">
          <span class="param-label">自耗电量:</span>
          <span class="param-value"
            >{{
              formatNumber(systemParams.selfConsumptionElectricity)
            }}
            kWh/天</span
          >
        </div>
        <div class="param-item">
          <span class="param-label">变压器容量:</span>
          <span class="param-value"
            >{{ formatNumber(systemParams.transformerCapacity) }} kVA</span
          >
        </div>
      </div>
    </div>

    <!-- 电价曲线 -->
    <div class="section price-curve" v-if="showPriceCurve">
      <div class="section-title">
        电价曲线
        <span v-if="finalResultData?.electricPricePlanMonth" class="month-info">
          （{{ finalResultData.electricPricePlanMonth }}月）
        </span>
      </div>
      <div class="curve-chart">
        <nt-echart :options="priceCurveOptions" />
      </div>
    </div>

    <!-- 历史负荷 -->
    <div class="section load-curve" v-if="historicalLoadData.length">
      <div class="section-title load-title">
        <span>历史负荷</span>
        <el-select
          v-model="selectedLoadDay"
          size="small"
          placeholder="请选择日期"
          @change="handleLoadDayChange"
        >
          <el-option
            v-for="item in historicalLoadData"
            :key="item.day"
            :label="item.day"
            :value="item.day"
          />
        </el-select>
      </div>
      <div class="curve-chart">
        <nt-echart :options="loadCurveOptions" />
      </div>
    </div>
  </div>
</template>

<script>
import ntEchart from '@/components/nt-echart.vue'

export default {
  name: 'ViewResult',
  components: {
    ntEchart
  },
  props: {
    formData: {
      type: Object,
      default: () => ({})
    },
    resultData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      priceCurveOptions: {},
      loadCurveOptions: {},
      selectedLoadDay: ''
    }
  },
  computed: {
    showPriceCurve() {
      return (
        this.finalResultData?.electricPricePlanJson &&
        this.finalResultData?.electricPricePlanMonth
      )
    },
    // 兼容从 formData 中获取 resultData
    finalResultData() {
      // 优先使用 resultData prop，然后是 formData.resultData
      const data = this.resultData || this.formData?.resultData || {}
      console.log('ViewResult - resultData prop:', this.resultData)
      console.log(
        'ViewResult - formData.resultData:',
        this.formData?.resultData
      )
      console.log('ViewResult - finalResultData:', data)
      console.log('ViewResult - suggestPlanCapacity:', data.suggestPlanCapacity)
      console.log('ViewResult - pcsRecommendValue:', data.pcsRecommendValue)
      console.log(
        'ViewResult - expectedInvestReturnPeriod:',
        data.expectedInvestReturnPeriod
      )
      console.log(
        'ViewResult - avgDayChargeDischargeTimes:',
        data.avgDayChargeDischargeTimes
      )
      return data
    },
    // 获取系统参数，优先使用 resultData（第四步返回的完整数据），否则使用 formData 中的分步数据
    systemParams() {
      const result = this.finalResultData
      // 如果 resultData 存在且包含系统参数，优先使用
      if (result && Object.keys(result).length > 0) {
        return {
          futureLoadGrowthRatio:
            result.futureLoadGrowthRatio ??
            this.formData?.stepTwoData?.futureLoadGrowthRatio,
          batteryEfficiency:
            result.batteryEfficiency ??
            this.formData?.stepFourData?.batteryEfficiency,
          antiOverloadFlag:
            result.antiOverloadFlag ??
            this.formData?.stepThreeData?.antiOverloadFlag,
          fullChargeFullDischargeDay:
            result.fullChargeFullDischargeDay ??
            this.formData?.stepTwoData?.fullChargeFullDischargeDay,
          pcsEfficiency:
            result.pcsEfficiency ?? this.formData?.stepFourData?.pcsEfficiency,
          backflowPreventionFlag:
            result.backflowPreventionFlag ??
            this.formData?.stepThreeData?.backflowPreventionFlag,
          singleWattCost:
            result.singleWattCost ??
            this.formData?.stepFourData?.singleWattCost,
          otherEfficiency:
            result.otherEfficiency ??
            this.formData?.stepFourData?.otherEfficiency,
          chargeDischargeTimesType:
            result.chargeDischargeTimesType ??
            this.formData?.stepThreeData?.chargeDischargeTimesType,
          dischargeDepth:
            result.dischargeDepth ??
            this.formData?.stepFourData?.dischargeDepth,
          selfConsumptionElectricity:
            result.selfConsumptionElectricity ??
            this.formData?.stepFourData?.selfConsumptionElectricity,
          transformerCapacity:
            result.transformerCapacity ??
            this.formData?.stepThreeData?.transformerCapacity
        }
      }
      // 否则使用 formData 中的分步数据
      return {
        futureLoadGrowthRatio:
          this.formData?.stepTwoData?.futureLoadGrowthRatio,
        batteryEfficiency: this.formData?.stepFourData?.batteryEfficiency,
        antiOverloadFlag: this.formData?.stepThreeData?.antiOverloadFlag,
        fullChargeFullDischargeDay:
          this.formData?.stepTwoData?.fullChargeFullDischargeDay,
        pcsEfficiency: this.formData?.stepFourData?.pcsEfficiency,
        backflowPreventionFlag:
          this.formData?.stepThreeData?.backflowPreventionFlag,
        singleWattCost: this.formData?.stepFourData?.singleWattCost,
        otherEfficiency: this.formData?.stepFourData?.otherEfficiency,
        chargeDischargeTimesType:
          this.formData?.stepThreeData?.chargeDischargeTimesType,
        dischargeDepth: this.formData?.stepFourData?.dischargeDepth,
        selfConsumptionElectricity:
          this.formData?.stepFourData?.selfConsumptionElectricity,
        transformerCapacity: this.formData?.stepThreeData?.transformerCapacity
      }
    },
    historicalLoadData() {
      if (
        this.finalResultData &&
        Array.isArray(this.finalResultData.loadDetailsList) &&
        this.finalResultData.loadDetailsList.length
      ) {
        return this.finalResultData.loadDetailsList
      }
      if (
        this.formData?.stepTwoData &&
        Array.isArray(this.formData.stepTwoData.loadDetailsList) &&
        this.formData.stepTwoData.loadDetailsList.length
      ) {
        return this.formData.stepTwoData.loadDetailsList
      }
      return []
    }
  },
  watch: {
    finalResultData: {
      handler() {
        this.updatePriceCurve()
        this.updateLoadCurve()
      },
      deep: true,
      immediate: true
    },
    'formData.stepTwoData': {
      handler() {
        this.updateLoadCurve()
      },
      deep: true
    }
  },
  mounted() {
    this.updatePriceCurve()
    this.updateLoadCurve()
  },
  methods: {
    formatNumber(value) {
      if (value === null || value === undefined || value === '') {
        return '-'
      }
      const num = Number(value)
      if (isNaN(num)) {
        return '-'
      }
      return num.toFixed(2)
    },
    formatPercentage(value) {
      if (value === null || value === undefined || value === '') {
        return '-'
      }
      return `${Number(value).toFixed(2)}%`
    },
    // 将时间字符串转换为分钟数
    timeToMinutes(time) {
      const [hour, minute] = time.split(':').map(Number)
      return hour * 60 + minute
    },
    // 将分钟数转换为时间字符串
    minutesToTime(minutes) {
      const hour = Math.floor(minutes / 60)
        .toString()
        .padStart(2, '0')
      const minute = (minutes % 60).toString().padStart(2, '0')
      return `${hour}:${minute}`
    },
    // 解析时间段字符串为时间段范围数组
    parseTimePeriods(timeStr, interval) {
      if (!timeStr || timeStr.trim() === '') {
        return []
      }

      // 将时间段字符串转换为时间数组（格式：HHmm -> HH:mm）
      const timeArray = timeStr
        .split(',')
        .map((t) => {
          const trimmed = t.trim()
          if (trimmed.length === 4) {
            return `${trimmed.substring(0, 2)}:${trimmed.substring(2, 4)}`
          }
          return null
        })
        .filter((t) => t !== null)
        .sort()

      if (timeArray.length === 0) {
        return []
      }

      // 将时间转换为分钟数数组
      const minutesArray = timeArray.map((time) => this.timeToMinutes(time))

      // 找出连续的时间段
      const ranges = []
      let rangeStart = minutesArray[0]
      let rangeEnd = minutesArray[0] + interval

      for (let i = 1; i < minutesArray.length; i++) {
        const currentMinutes = minutesArray[i]
        const expectedNext = rangeEnd

        // 检查是否连续（当前时间点应该等于上一个时间段的结束时间）
        if (currentMinutes === expectedNext) {
          // 连续，扩展结束时间
          rangeEnd = currentMinutes + interval
        } else {
          // 不连续，保存当前时间段，开始新的时间段
          ranges.push([
            this.minutesToTime(rangeStart),
            this.minutesToTime(rangeEnd)
          ])
          rangeStart = currentMinutes
          rangeEnd = currentMinutes + interval
        }
      }

      // 保存最后一个时间段
      ranges.push([
        this.minutesToTime(rangeStart),
        this.minutesToTime(rangeEnd)
      ])

      return ranges
    },
    // 根据电价配置生成24小时的电价曲线数据
    generatePriceCurveData() {
      const result = this.finalResultData
      if (
        !result ||
        !result.electricPricePlanJson ||
        !result.electricPricePlanMonth
      ) {
        return new Array(24).fill(0)
      }

      try {
        // 解析 priceJson
        const priceJson = JSON.parse(result.electricPricePlanJson)
        // 根据月份获取对应的数据，月份键格式为 M1, M2, ..., M12
        const monthKey = `M${result.electricPricePlanMonth}`
        console.log('电价曲线 - 月份键:', monthKey)
        console.log('电价曲线 - 可用月份:', Object.keys(priceJson))
        const monthData = priceJson[monthKey]

        if (!monthData || !Array.isArray(monthData) || monthData.length === 0) {
          console.warn('电价曲线 - 未找到对应月份的数据:', monthKey)
          return new Array(24).fill(0)
        }

        console.log('电价曲线 - 月份数据:', monthData)

        const data = monthData[0]
        const interval = parseInt(data.SJJG || 15, 10)

        // 初始化24小时数据，每个小时有60个数据点（每分钟一个点）
        const minutesPerDay = 24 * 60
        const priceData = new Array(minutesPerDay).fill(0)

        // 费率类型映射
        const rateTypes = [
          {
            key: 'FL1',
            price: parseFloat(data.FL1DJ) || 0,
            periods: data.FL1QJ || ''
          },
          {
            key: 'FL2',
            price: parseFloat(data.FL2DJ) || 0,
            periods: data.FL2QJ || ''
          },
          {
            key: 'FL3',
            price: parseFloat(data.FL3DJ) || 0,
            periods: data.FL3QJ || ''
          },
          {
            key: 'FL4',
            price: parseFloat(data.FL4DJ) || 0,
            periods: data.FL4QJ || ''
          },
          {
            key: 'FL5',
            price: parseFloat(data.FL5DJ) || 0,
            periods: data.FL5QJ || ''
          }
        ]

        // 遍历每个费率类型，填充对应时段的价格
        rateTypes.forEach((rateType) => {
          if (rateType.periods && rateType.periods.trim() !== '') {
            const timePeriods = this.parseTimePeriods(
              rateType.periods,
              interval
            )
            console.log(
              `电价曲线 - ${rateType.key} 时段:`,
              timePeriods,
              '价格:',
              rateType.price
            )
            timePeriods.forEach((period) => {
              if (period && Array.isArray(period) && period.length === 2) {
                const [startTime, endTime] = period
                if (startTime && endTime) {
                  const startMinutes = this.timeToMinutes(startTime)
                  const endMinutes = this.timeToMinutes(endTime)

                  // 填充该时间段内的所有分钟
                  for (
                    let minutes = startMinutes;
                    minutes < endMinutes;
                    minutes++
                  ) {
                    if (minutes >= 0 && minutes < minutesPerDay) {
                      priceData[minutes] = rateType.price
                    }
                  }
                }
              }
            })
          }
        })

        // 将每分钟的数据聚合为每小时的数据（取每小时第一个数据点的值）
        const hourlyData = []
        for (let hour = 0; hour < 24; hour++) {
          const hourStartMinutes = hour * 60
          hourlyData.push(priceData[hourStartMinutes] || 0)
        }

        return hourlyData
      } catch (error) {
        console.error('解析电价数据失败:', error)
        return new Array(24).fill(0)
      }
    },
    // 生成 96 个时间刻度（按 15 分钟）
    generateTimeLabels() {
      const labels = []
      for (let i = 0; i < 96; i++) {
        const totalMinutes = i * 15
        labels.push(this.minutesToTime(totalMinutes))
      }
      return labels
    },
    // 更新电价曲线
    updatePriceCurve() {
      const hours = Array.from({ length: 24 }, (_, idx) =>
        idx.toString().padStart(2, '0')
      )
      const priceData = this.generatePriceCurveData()

      // 计算Y轴的最大值（价格的最大值，向上取整到合适的值）
      const maxPrice = Math.max(...priceData, 0)
      const yAxisMax = maxPrice > 0 ? Math.ceil(maxPrice * 1.2) : 1

      console.log('电价曲线 - priceData:', priceData)
      console.log('电价曲线 - maxPrice:', maxPrice)
      console.log('电价曲线 - yAxisMax:', yAxisMax)

      this.priceCurveOptions = {
        color: ['#409EFF'],
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const item = params[0]
            return `${item.axisValue}时：${item.data} 元/kWh`
          }
        },
        grid: {
          left: 40,
          right: 20,
          top: 40,
          bottom: 30,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hours,
          boundaryGap: false,
          axisLabel: {
            formatter: (val) => `${val}时`
          }
        },
        yAxis: {
          type: 'value',
          name: '元/kWh',
          min: 0,
          max: yAxisMax,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#dcdfe6'
            }
          }
        },
        series: [
          {
            name: '电价',
            type: 'line',
            step: 'end',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            itemStyle: {
              color: '#409EFF',
              borderColor: '#fff',
              borderWidth: 1.5
            },
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.2)'
            },
            data: priceData
          }
        ]
      }
    },
    // 更新历史负荷曲线
    updateLoadCurve() {
      const loadData = this.historicalLoadData
      if (!loadData.length) {
        this.loadCurveOptions = {}
        this.selectedLoadDay = ''
        return
      }

      if (!this.selectedLoadDay) {
        this.selectedLoadDay = loadData[0]?.day || ''
      }

      const currentDayData =
        loadData.find((item) => item.day === this.selectedLoadDay) ||
        loadData[0]

      const timeLabels = this.generateTimeLabels()
      const values = (currentDayData.loadList || []).map((v) => Number(v) || 0)
      while (values.length < 96) {
        values.push(0)
      }

      this.loadCurveOptions = {
        color: ['#67C23A'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: { show: false },
        grid: {
          left: 50,
          right: 20,
          top: 50,
          bottom: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeLabels,
          axisLabel: {
            formatter: (val) => val
          }
        },
        yAxis: {
          type: 'value',
          name: 'kW',
          min: 0,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#dcdfe6'
            }
          }
        },
        series: [
          {
            name: currentDayData.day || '历史负荷',
            type: 'line',
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 2
            },
            areaStyle: {
              color: 'rgba(103, 194, 58, 0.15)'
            },
            data: values.slice(0, 96)
          }
        ]
      }
    },
    handleLoadDayChange() {
      this.updateLoadCurve()
    }
  }
}
</script>

<style lang="scss" scoped>
.view-result {
  .section {
    margin-bottom: 30px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }

  // 系统建议配置
  .recommended-config {
    .config-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      margin-bottom: 20px;

      .config-item {
        background: #2e4860;
        border: 1px solid #3cb7e9;
        border-radius: 4px;
        padding: 20px;
        text-align: center;
        position: relative;

        .config-label {
          font-size: 14px;
          color: #e0e0e0;
          margin-bottom: 10px;
        }

        .config-value {
          font-size: 24px;
          font-weight: bold;
          color: #fff;
          margin-bottom: 5px;
        }

        .config-desc {
          font-size: 12px;
          color: #ff6b6b;
          margin-top: 5px;
        }
      }
    }
  }

  // 系统参数
  .system-params {
    .params-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px 40px;

      .param-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #e0e0e0;

        .param-label {
          font-size: 14px;
          color: #606266;
        }

        .param-value {
          font-size: 14px;
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }

  // 电价曲线
  .price-curve {
    margin-top: 30px;

    .section-title {
      .month-info {
        font-size: 14px;
        font-weight: normal;
        color: #909399;
        margin-left: 8px;
      }
    }

    .curve-chart {
      height: 260px;
      border-radius: 4px;
      padding: 15px 20px;
      background: #fff;
    }
  }

  // 历史负荷
  .load-curve {
    margin-top: 30px;

    .load-title {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-select {
        width: 180px;
      }
    }

    .section-title {
      .month-info {
        font-size: 14px;
        font-weight: normal;
        color: #909399;
        margin-left: 8px;
      }
    }

    .curve-chart {
      height: 320px;
      border-radius: 4px;
      padding: 15px 20px;
      background: #fff;
    }
  }
}
</style>
